﻿if(typeof Object.values !== 'function') {
	Object.values = function values(obj) {
		var vals = [];
		for(var key in obj) {
			if(obj.hasOwnProperty(key) === true) {
				vals.push(obj[key]);
			}
		}
		return vals;
	};
}
//定义app
var myApp = angular.module('shoppingCart', ['ng', 'ui.router'])
	.run(function($rootScope, $state, $stateParams, $location) {
		$rootScope.$state = $state;
		$rootScope.$stateParams = $stateParams;
	})
	.config(function($stateProvider, $urlRouterProvider) {
		$urlRouterProvider.otherwise('/home');
		$stateProvider.state('home', {
			url: '/home', //路由
			templateUrl: 'View/Home.aspx',
			controller: 'HomeController'
		})
	});

myApp.controller('HomeController', function($scope, $zlan) {
	$scope.TotalPrice = 0;
	$scope.FinallyPrice = 0;
	$scope.DiscountPrice = 0;
	$scope.ShippingPrice = 0;
	$scope.RuleContainer = {};
	$scope.RuleContainerList = [];
	$scope.RuleList = [];
	$scope.ProductList = [];
	$scope.ProductListIsNull = false;
	$scope.ProductSelectAll = true;
	$scope.ProductSelect = {};
	$scope.ProductSelectSkuList = [];
	$scope.submitDisabled = '';
	var uqdateProductSelectList = function() {

		$scope.RuleContainerList.forEach(function(RuleContainerData) {
			RuleContainerData.ProductSelectList = RuleContainerData.ProductList.filter(function(ProductData) {
				return $scope.ProductSelect[ProductData.ProductSkuNo];
			});
			//			console.log(RuleContainerData.ProductList)
		});

		var ProductSelectSkuList = [];
		for(var ProductSkuNo in $scope.ProductSelect) {
			if($scope.ProductSelect[ProductSkuNo] === true) {
				ProductSelectSkuList.push(ProductSkuNo);
			}
		}
		$scope.ProductSelectSkuList = ProductSelectSkuList;
		return ProductSelectSkuList;
	};

	var init = function() {
		$zlan.executeCommand('Member.LoadPromotionList', {
			Kind: 'shop'
		}, function(result) {

			$scope.RuleContainer = {};
			$scope.RuleList = result.Result.DiscountResult.PromotionList.sort(function(RuleData1, RuleData2) {
				var wz = [null, 3, 1, 0];
				return wz.indexOf(RuleData1.Type) < wz.indexOf(RuleData2.Type);
			});
			$scope.ProductList = [];
			$scope.ProductSelect = {};
			$scope.RuleList.forEach(function(RuleData) {
				RuleData.Mark = RuleData.DeptCode + '-' + (RuleData.RelationCode && RuleData.RelationCode !== '0' ? RuleData.RelationCode : '0_' + RuleData.RuleId);
				RuleData.ProductListInit = RuleData.ProductList.map(function(ProductData) {
					const ProductSkuNo = ProductData.ProductSkuNo;
					const isExist = $scope.ProductList.some(function(ProductData) {
						return ProductData.ProductSkuNo === ProductSkuNo;
					});
					if(!isExist) {
						ProductData.RuleList = $scope.RuleList.filter(function(RuleData) {
							return RuleData.ProductList.some(function(ProductData) {
								return ProductData.ProductSkuNo === ProductSkuNo;
							});
						});
						$scope.ProductList.push(ProductData);

						ProductData.SalePriceFomat = fomatFloat(ProductData.SalePrice);
						ProductData.ThumbnailImgFirstThumb = $zlan.thumbImage(ProductData.ThumbnailImg);

						try {
							var SkuParam = JSON.parse(ProductData.SkuParamCode);
							if(SkuParam[0]) {
								ProductData.SkuParamTitle = SkuParam.map(function(Item) {
									return Item.ItemName;
								}).join(', ');
							}
						} catch(error) {
							ProductData.SkuParamTitle = '';
						}

						$scope.ProductSelect[ProductSkuNo] = true;
					}
					return ProductData;
				});
			});

			$scope.ProductList.forEach(function(ProductData) {
				var key = ProductData.RuleList.map(function(RuleData) {
					return RuleData.Mark;
				}).join('|');
				if(!$scope.RuleContainer[key]) {
					$scope.RuleContainer[key] = {
						RuleGroup: {},
						RuleList: ProductData.RuleList,
						ProductSelectList: [],
						ProductList: [],
					};
					ProductData.RuleList.forEach(function(RuleData) {
						if(!$scope.RuleContainer[key].RuleGroup[RuleData.Mark]) {
							$scope.RuleContainer[key].RuleGroup[RuleData.Mark] = {
								Index: 1,
								RuleData: {},
								Status: false,
								Type: RuleData.Type,
								RuleList: [],
							};
						}
						$scope.RuleContainer[key].RuleGroup[RuleData.Mark].RuleList.push(RuleData);
					});
				}
				$scope.RuleContainer[key].ProductList.push(ProductData);
				$scope.RuleContainer[key].RuleGroupList = Object.values($scope.RuleContainer[key].RuleGroup).sort(function(RuleGroupData1, RuleGroupData2) {
					var wz = [null, 3, 1, 0];
					return wz.indexOf(RuleGroupData1.Type) < wz.indexOf(RuleGroupData2.Type);
				});

				$scope.RuleContainer[key].RuleGroupFirst = $scope.RuleContainer[key].RuleGroupList[0];
				$scope.RuleContainer[key].RuleGroupRemaining = $scope.RuleContainer[key].RuleGroupList.slice(1);

			});

			$scope.RuleContainerList = Object.values($scope.RuleContainer)

			updateCycle($scope.RuleList);

			updateProductListIsNull();

		});
	};

	/** 保留两位小数 */
	var fomatFloat = $scope.fomatFloat = function(x) {
		var f = parseFloat(x);
		if(isNaN(f)) {
			return false;
		}
		var f = Math.round(x * 100) / 100;
		var s = f.toString();
		var rs = s.indexOf('.');
		if(rs < 0) {
			rs = s.length;
			s += '.';
		}
		while(s.length <= rs + 2) {
			s += '0';
		}
		return s;
	};

	// 更新产品列表是否为空
	var updateProductListIsNull = function() {
		if($scope.ProductList.length <= 0) {
			$scope.ProductListIsNull = true;
		} else {
			$scope.ProductListIsNull = false;
		}
	};

	const updateCycle = function(RequestRuleList) {

		RequestRuleList = RequestRuleList || [];

		uqdateProductSelectList();

		RequestRuleList.forEach(function(RequestRuleData) {
			const RuleData = $scope.RuleList.find(function(RuleData) {
				return RuleData.RuleId === RequestRuleData.RuleId;
			});
			if(RuleData) {
				Object.assign(RuleData, RequestRuleData);
			}
		});

		$scope.RuleContainerList.forEach(function(RuleContainerData) {
			RuleContainerData.RuleGroupList.forEach(function(RuleGroupData) {
				if(!RuleContainerData.ProductSelectList.length) {
					RuleGroupData.Index = 0;
					RuleGroupData.RuleData = RuleGroupData.RuleList[0];
					RuleGroupData.Status = false;
				} else {
					var Index = RuleGroupData.RuleList.findIndex(function(RuleData, Index) {
						if(RuleData.Type === 3) {
							return RuleData.Status === 1 && RuleData.OrderUnable === false;
						}
						return RuleData.Status === 1;
					});
					if(Index >= 0) {
						RuleGroupData.Index = Index;
						RuleGroupData.RuleData = RuleGroupData.RuleList[Index];
						RuleGroupData.Status = true;
					} else {
						RuleGroupData.Index = 0;
						RuleGroupData.RuleData = RuleGroupData.RuleList[0];
						RuleGroupData.Status = false;
					}
				}
			});
		});

		updatePrice();
		detectionSubmitDisabled();

		// console.log($scope.RuleContainer);

	};

	// 更新价格
	var updatePrice = function() {

		$scope.TotalPrice = 0;
		$scope.FinallyPrice = 0;
		$scope.DiscountPrice = 0;
		$scope.ShippingPrice = 0;

		$scope.RuleContainerList.forEach(function(RuleContainerData) {
			RuleContainerData.RuleGroupList.forEach(function(RuleGroupData) {
				if(RuleGroupData.Status) {
					$scope.DiscountPrice += RuleGroupData.RuleData.DiscountFee;
					$scope.ShippingPrice += RuleGroupData.RuleData.ShippingFee;
				}
			});
		});

		$scope.ProductList.forEach(function(ProductData) {
			if($scope.ProductSelect[ProductData.ProductSkuNo] === true) {
				$scope.TotalPrice += ProductData.Counter * ProductData.SalePrice;
			}
		});

		$scope.FinallyPrice = $scope.TotalPrice + $scope.ShippingPrice - $scope.DiscountPrice;
	};

	// 禁止下单条件
	var detectionSubmitDisabled = function() {
		$scope.submitDisabled = '';
		if($scope.FinallyPrice <= 0) {
			return $scope.submitDisabled = '请选择产品！';
		}
		// else if ($scope.FinallyPrice > 3000) {
		//     return $scope.submitDisabled = '订单总金额不能超过3000元！';
		// }
		$scope.RuleContainerList.some(function(RuleContainerData) {
			if(!RuleContainerData.ProductSelectList.length) {
				return false
			}
			return RuleContainerData.RuleGroupList.some(function(RuleGroupData) {
				if(RuleGroupData.Type === 3 && !RuleGroupData.Status) {
					$scope.submitDisabled = '含有未满足结算商品！';
					return true;
				}
				return false;
			});

		});
	};

	init();

	// 全选
	var selectedAllChange = $scope.selectedAllChange = function() {
		$scope.ProductSelectAll = !$scope.ProductSelectAll;
		if($scope.ProductSelectAll) {
			$scope.ProductList.forEach(function(ProductData) {
				$scope.ProductSelect[ProductData.ProductSkuNo] = true;
			});
		} else {
			$scope.ProductList.forEach(function(ProductData) {
				$scope.ProductSelect[ProductData.ProductSkuNo] = false;
			});
		}
		updateSelectProduct();
	};

	// 选择产品
	var updateSelectProduct = $scope.updateSelectProduct = function() {
		updateCycle();
		$zlan.executeCommand('Member.LoadPromotionList', {
			ProductSkuNo: $scope.ProductSelectSkuList,
			Kind: 'shop'
		}, function(result) {
			updateCycle(result.Result.DiscountResult.PromotionList);
		});
	};
	// 产品添加数量
	var addProductQuantity = $scope.addProductQuantity = function(ProductData, Counter) {
		ProductData.Counter += Counter;
		setProductQuantity(ProductData, ProductData.Counter);
	};
	// 产品修改数量
	var setProductQuantity = $scope.setProductQuantity = function(ProductData, Counter) {
		Counter = Number(Counter);
		if(isNaN(Counter)) Counter = 1;
		if(Counter < 1) Counter = 1;
		if(Counter > 99) Counter = 99;
		$zlan.executeCommand('Member.SelectProduct', {
			ProductList: [{
				ProductSkuCode: ProductData.ProductSkuNo,
				Counter: Counter,
				Increment: 0
			}]
		}, function(result) {
			ProductData.Counter = Counter;
			updateSelectProduct();
		});
	};
	// 删除选中的产品
	var removeProduct = $scope.removeProduct = function() {
		const ProductSelectList = $scope.ProductSelectSkuList;
		if(ProductSelectList.length <= 0) {
			return $scope.showTips("没有勾选的商品", 1500);
		}
		confirmDialog('确定要删除勾选的商品吗？', function() {
			$zlan.executeCommand('Member.RemoveProduct', {
				SkuCodeList: ProductSelectList
			}, function(result) {
				$scope.showTips("删除商品成功！", 500, function() {
					init();
				});
			});
		});
	};

	// 提交
	var onSubmit = $scope.onSubmit = function() {
		if($scope.submitDisabled) {
			return $scope.showTips($scope.submitDisabled, 1500);
		}
		$zlan.executeCommand('Member.ConfirmSelectProduct', {
			SkuCodeList: $scope.ProductSelectSkuList
		}, function(result) {
			window.location.href = "/Wap/Shop/SubmitOrder.aspx"
		});
	};

	//showTips
	$scope.showTips = function(text, time, callback) {

		var htmlCon = '';
		if(text != '') {
			htmlCon = '<div class="ShowTis">' + text + '</div>';
		}
		$('body').prepend(htmlCon);
		if(time == '' || time == undefined) {
			time = 1500;
		}
		setTimeout(function() {
			$('.ShowTis').remove();
			if(callback) {
				callback();
			};
		}, time);
	};

	//推荐商品
	$scope.likeData = {
		pageSize: 8,
		pageNum: 0,
		raw: [],
		isLoad: false,
		isComplete: false,
    	statistics = function (name, src) {
		    var path = 'shoppingcart|home|likeData|' + src.join('|');//路径
		    _hmt.push(['_trackEvent', path, 'click', name]);
		},
		next: function () {
			if ($scope.likeData.isLoad || $scope.likeData.isComplete) {
				return ;
			}
			$scope.likeData.isLoad = true;
			$scope.likeData.pageNum ++;
			$zlan.getReferenceProductList($scope.likeData.pageNum, $scope.likeData.pageSize).then(function (list) {
				for(var i = 0; i < list.length; i++) {
					var item = list[i];
					item.ProductImage = $zlan.thumbImage(item.ProductImage);
					$scope.likeData.raw.push(item)
				}
				if (list.length < $scope.likeData.pageSize) {
					$scope.likeData.isComplete = true;
					$(window).off('scroll');
				}
				$scope.likeData.isLoad = false;
				$scope.$apply();
			});
		}
	};

	$scope.likeData.next();

	//监听滚动条事件
	$(window).scroll(function() {
		var scrollTop = $(this).scrollTop();
		var scrollHeight = $(document).height();
		var windowHeight = $(window).height();
		console.log(windowHeight);
		if(scrollTop + windowHeight >= scrollHeight - 200) {
			$scope.likeData.next();
		}
	});
	

});

//定义通用服务
myApp.factory('$zlan', ['$http', '$timeout', 'cmsServiceIp', function($http, $timeout, cmsServiceIp) {
	var layerLen = 0;
	var layerIndex = null;
	var _execute = function(key, param, callback) {
		layerLen += 1;
		if(layerIndex === null) {
			layerIndex = layer.open({
				type: 2,
				shadeClose: false,
				shade: 'background-color: rgba(0,0,0,.1)'
			});
		}
		$http({
			url: '/Interface/ajax/CommandService.aspx?key=' + key,
			method: 'POST',
			params: {
				param: param
			}
		}).then(function successCallback(response) {
			if(response.data.ErrorCode == '0000') {
				$timeout(function() {
					callback(response.data);
				});
			} else if(response.data.ErrorCode == '0109') {
				//跳转登录
				location.href = "/wap/member/LoginWeixin.aspx?goto=" + encodeURIComponent("/wap/ShoppingCart/");
			}
			layerLen -= 1;
			if(layerLen === 0) {
				layer.close(layerIndex);
				layerIndex = null;
			}
		}, function errorCallback(response) {})
	}
	
	var getReferenceProductList = function (page, size) {
		return $.ajax({
			url: cmsServiceIp + "/api/Product/GetReferenceProductList",
			method: 'post',
			data: {
				"ReferenceKind": "SHOPPINGCART_TJ",
				"ReferenceCode": '394',
				"PageIndex": page || 1,
				"PageSize": size || 90
			}
		}).then(function($res) {
			return $res.Data;
		});
	};

	var _thumbImage = function(json) {
		try {
			var fileArr = $.parseJSON(json);
			return($.cookie('imagesvr') ? $.cookie('imagesvr') : '') + fileArr[0].FilePath + '.thumb.' + fileArr[0].FileExt;
		} catch(e) {
			return '';
		}
	}

	return({
		executeCommand: _execute,
		getReferenceProductList: getReferenceProductList,
		thumbImage: _thumbImage
	});
}]);